import { getUserInfo, login, getUserDetail } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken, setTime } from '@/utils/auth'

const state = {
  token: getToken(), // token字符串
  userInfo: {} // 存储用户信息
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
    setTime(Date.now())
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
    // console.log(state.userInfo)
  },
  updatePhoto(state, staffPhoto) {
    state.userInfo.staffPhoto = staffPhoto
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(context, payload) {
    const data = await login(payload)
    context.commit('setToken', data)
  },
  async getUserInfo({ commit }) {
    const res1 = await getUserInfo()
    const res2 = await getUserDetail(res1.userId) // 获取头像
    commit('setUserInfo', {
      ...res1, ...res2
    })
  },
  // 退出的action
  logout(context) {
    // 1. 移除vuex个人信息
    context.commit('removeUserInfo')
    // 2. 移除token信息
    context.commit('removeToken')
    // 3. 重置路由
    resetRouter()
    // 4. 重置 vuex 中的路由信息
    context.commit('permission/setRoutes', [], { root: true })
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

